import java.util.ArrayList;
import java.util.List;

/**
 * 39. 组合总和
 * https://leetcode.cn/problems/combination-sum/description/
 */
class Solution {
    List<Integer> path;
    List<List<Integer>> ret;
    int target;
    int[] candidates;
    public List<List<Integer>> combinationSum(int[] _candidates, int _target) {
        path = new ArrayList<>();
        ret = new ArrayList<>();
        target = _target;
        candidates = _candidates;
        dfs(0, 0);
        return ret;
    }
    //老师的写法
    void dfs(int pos, int sum) {
        if(sum == target) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if(sum > target || pos == candidates.length) return;
        for(int i = pos; i < candidates.length; i++) {
            path.add(candidates[i]);
            dfs(i, sum + candidates[i]);
            path.remove(path.size() - 1);
        }
    }
    //自己的（全局的想法）
    void dfs1(int pos, int sum) {
        if(sum == target) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if(sum > target) return;
        for(int i = 0; i < candidates.length; i++) {
            if(i < pos) continue;
            path.add(candidates[i]);
            sum += candidates[i];
            dfs1(i, sum);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
    //枚举 num[pos] 使用多少个的思路
    void dfs3(int pos, int sum) {
        if(sum == target) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if(sum > target || pos == candidates.length) return;
        //枚举 num[pos] 使用多少个
        for(int i = 0; i * candidates[pos] <= target; i++) {
            if(i != 0) path.add(candidates[pos]);
            dfs3(pos + 1, sum + i * candidates[pos]);
        }
        //恢复现场
        for(int i = 1; i * candidates[pos] <= target; i++) {
            path.remove(path.size() - 1);
        }
    }
}